﻿using BTNode = GX.BTTree.BTNode;
using BTNodeContainer = GX.BTTree.BTNodeContainer;

namespace GX
{
    public class BTNodeParallel:BTNodeContainer
    {
        int _numTotal;
        int _numSkip;
        int _numDone;
        int _numSuccess;
        protected override void OnEnter(bool isRestart)
        {
            _numTotal = this.numChildren;
            _numSkip = 0;
            _numDone = 0;
            _numSuccess = 0;
            for (int i = 0; i < _numTotal; ++i)
            {
                var node = GetChildAt(i);
                if (node.Evaluate())
                    node.Start(OnChildDone);
                else
                    ++_numSkip;
            }
            CheckEnd();
        }
        void CheckEnd()
        {
            if (_numDone + _numSkip == _numTotal)
            {
                if (_numSuccess == _numDone)
                    this.Finish();
                else
                    this.Fail();
            }
        }
        protected override void OnExit()
        {
            if (this.isInterrupt)
            {
                for (int i = 0; i < _numTotal; ++i)
                {
                    var node = GetChildAt(i);
                    node.Stop();
                }
            }
        }
        protected override void OnChildDone(BTNode node)
        {
            if (this.isDone) return;

            ++_numDone;
            if (node.isSuccess)
                ++_numSuccess;
            CheckEnd();
        }
    }
}